package gold.digger;

import gold.vo.TreeNode;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC987 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public List<List<Integer>> verticalTraversal(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            Map<Integer, Map<Integer, List<Integer>>> map = new TreeMap<>();
            travelTree(root, 0, 0, map);
            for (Map<Integer, List<Integer>> colMap : map.values()) {
                List<Integer> list = new ArrayList<>();
                for (List<Integer> val : colMap.values()) {
                    TreeSet<Integer> set = new TreeSet<>();
                    set.addAll(val);
                    list.addAll(new ArrayList<>(set));
                }

                res.add(list);
            }

            return res;
        }

        public void travelTree(TreeNode root, int rx, int ry, Map<Integer, Map<Integer, List<Integer>>> map) {
            if (null == root) return;
            if (map.containsKey(rx)) {
                Map<Integer, List<Integer>> colMap = map.get(rx);
                if (colMap.containsKey(ry)) colMap.get(ry).add(root.val);
                else {
                    List<Integer> valList = new ArrayList<>();
                    valList.add(root.val);
                    colMap.put(ry, valList);
                }
            } else {
                Map<Integer, List<Integer>> colMap = new TreeMap<>();
                List<Integer> valList = new ArrayList<>();
                valList.add(root.val);
                colMap.put(ry, valList);
                map.put(rx, colMap);
            }

            travelTree(root.left, rx - 1, ry + 1, map);
            travelTree(root.right, rx + 1, ry + 1, map);
        }

    }

    public void run() {
        Solution solution = new Solution();
        TreeNode root = TreeNode.createTree("[0,5,1,9,null,2,null,null,null,null,3,4,8,6,null,null,null,7]");
        System.out.println(solution.verticalTraversal(root));
    }

    public static void main(String[] args) throws Exception {
        LC987 an = new LC987();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
